package com.remark.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.remark.config.RabbitMQConfig;
import com.remark.dto.Result;
import com.remark.entity.VoucherOrder;
import com.remark.mapper.VoucherOrderMapper;
import com.remark.service.ISeckillVoucherService;
import com.remark.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.remark.utils.RedisIdWorker;
import com.remark.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;
    
    @Resource
    private RabbitTemplate rabbitTemplate;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static{
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        // 获取订单ID
        long orderId = redisIdWorker.nextId("order");//生成订单id
        //1.执行Lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                UserHolder.getUser().getId().toString(),
                String.valueOf(orderId)
        );
        int r = result.intValue();
        if(r != 0){ //2.判断结果是否为0,不为0,代表没有购买资格
            return Result.fail(r==1 ? "库存不足":"不能重复下单！");
        }
        
        // 获取Redis中暂存的消息
        String messageKey = "seckill:message:" + orderId;
        Map<Object, Object> messageMap = stringRedisTemplate.opsForHash().entries(messageKey);
        if (messageMap.isEmpty()) {
            return Result.fail("订单信息获取失败");
        }
        
        // 发送消息到RabbitMQ
        rabbitTemplate.convertAndSend(
                RabbitMQConfig.VOUCHER_ORDER_EXCHANGE, 
                RabbitMQConfig.VOUCHER_ORDER_ROUTING_KEY, 
                messageMap
        );
        
        // 删除Redis中的临时消息
        stringRedisTemplate.delete(messageKey);
        
        // 获取代理对象
        this.proxy = (IVoucherOrderService) AopContext.currentProxy();
        //3.返回订单id
        return Result.ok(orderId);
    }
    
    // 使用RabbitMQ监听器接收消息
    @RabbitListener(queues = RabbitMQConfig.VOUCHER_ORDER_QUEUE)
    public void listenVoucherOrder(Map<String, Object> map) {
        try {
            // 将消息转换为VoucherOrder对象
            VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(map, new VoucherOrder(), false);
            
            // 在这里设置代理对象（确保每次都能获取到当前的AOP代理）
            this.proxy = (IVoucherOrderService) AopContext.currentProxy();
            
            // 处理订单
            handleVoucherOrder(voucherOrder);
        } catch (Exception e) {
            log.error("处理订单异常", e);
        }
    }

    private IVoucherOrderService proxy;
    
    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        //1.获取用户
        Long userId = voucherOrder.getUserId();
        //2.创建锁对象
        RLock lock = redissonClient.getLock("lock:order:"+userId);
        //3.获取锁
        boolean isLock = lock.tryLock();
        //4.判断是否获取锁成功
        if(!isLock) {
            log.error("不允许重复下单");
            return;
        }
        try {
            // 使用代理对象调用，确保事务生效
            if (proxy != null) {
                proxy.createVoucherOrder(voucherOrder);
            } else {
                // 直接调用，可能会导致事务失效
                log.warn("代理对象为null，直接调用方法，可能导致事务失效");
                createVoucherOrder(voucherOrder);
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * 创建订单
     * @param voucherOrder
     */
    //保证订单创建和库存扣减的原子性
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //一人一单的实现
        Long userId = voucherOrder.getUserId();//获取当前用户id

        //查询当前用户是否已经购买过该优惠券（通过查询订单订单数量）
        int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        //判断是否存在
        if (count > 0) {
            //用户已经购买过该优惠券，返回异常
            log.error("用户已经购买过该优惠券");
            return;
        }

        //库存充足，扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock=stock-1")
                .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0)
                .update();
        if (!success) {
            //扣减失败
            log.error("库存不足");
            return;
        }
        //创建订单
        save(voucherOrder);
    }
}
